﻿using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using UDS.Components;

namespace UDS.SubModule.CM
{
    /// <summary>
    /// ClientContact 的摘要说明。
    /// </summary>
    public partial class ClientContactPage : Page
    {
        private int _clientId;
        private int _contactId;

        protected int CurrentClientID
        {
            get { return _clientId; }
        }

        private void Page_Load(object sender, EventArgs e)
        {
            // 在此处放置用户代码以初始化页面
            var cm = new Components.CM();
            SqlDataReader dr;

            if (!Page.IsPostBack)
            {
                tbx_contacttime.Text = DateTime.Now.ToShortDateString();
                tbx_nextcontacttime.Text = DateTime.Now.AddDays(1).ToShortDateString();
                _clientId = Int32.Parse(string.IsNullOrEmpty(Request.QueryString["ClientID"]) ? "-1" : Request.QueryString["ClientID"]);

                pnl_clientselect.Visible = true;
                //绑定客户列表
                dr = cm.GetMyClients(SiteContext.Current.UserID);
                ddl_ClientName.DataSource = dr;
                ddl_ClientName.DataValueField = "id";
                ddl_ClientName.DataTextField = "name";
                ddl_ClientName.DataBind();
                dr.Close();
                if (_clientId != -1)
                {
                    if (ddl_ClientName.Items.Count != 0)
                    {
                        foreach (ListItem li in ddl_ClientName.Items)
                        {
                            if (li.Value == _clientId.ToString())
                            {
                                li.Selected = true;
                            }
                            else
                            {
                                li.Selected = false;
                            }
                        }
                        ViewState["ClientID"] = _clientId;
                    }
                    //显示销售人员
                    ClientInfo client = cm.GetClientAllInfo(_clientId);
                    var staffInfo = Staff.GetStaffInfo(client.AddManID);
                    if (staffInfo != null)
                    {
                        ltl_AddMan.Text = staffInfo.RealName;
                    }
                }
                else
                {
                    if (ddl_ClientName.Items.Count != 0)
                    {
                        _clientId = Int32.Parse(ddl_ClientName.Items[0].Value);
                        ViewState["ClientID"] = _clientId;
                    }
                    else
                    {
                        ViewState["ClientID"] = _clientId;
                    }
                }
                DisplayClientInfo();
                BindData();
                ViewState["ContactID"] = _contactId.ToString();
            }
            else
            {
                _clientId = Int32.Parse(ViewState["ClientID"].ToString());
                _contactId = Int32.Parse(ViewState["ContactID"].ToString());
            }


            tbx_contacttime.Attributes["onfocus"] = "setday(this)";
            tbx_nextcontacttime.Attributes["onfocus"] = "setday(this)";
        }

        private void BindData()
        {
            string staffids = "";
            var staff = new Components.Staff();

            //绑定该客户的联系人
            var db = new Database();
            var prams = new[]
            {
                Database.MakeInParam("@clientid", SqlDbType.Int, 4, _clientId)
            };
            using (var dr_ClientLinkman = db.RunDataReader("dbo.sproc_CM_GetAllLinkmanFromClient", prams))
            {
                lbx_ClientLinkman.DataSource = dr_ClientLinkman;
                lbx_ClientLinkman.DataTextField = "Name";
                lbx_ClientLinkman.DataValueField = "id";
                lbx_ClientLinkman.DataBind();
                dr_ClientLinkman.Close();
            }

            //绑定协同人员候选列表
            for (int i = 0; i < lbx_Cooperater.Items.Count; i++)
            {
                staffids += lbx_Cooperater.Items[i].Value + ",";
            }
            if (staffids.Length != 0)
            {
                staffids = staffids.Substring(0, staffids.Length - 1);
            }

            using (var dr_staff = staff.GetRemainStaff(staffids))
            {
                lbx_Staff.DataSource = dr_staff;
                lbx_Staff.DataTextField = "realname";
                lbx_Staff.DataValueField = "staff_id";
                lbx_Staff.DataBind();
                dr_staff.Close();
            }

            ControlClientContactHistory1.ClientID = _clientId;
            ControlClientContactHistory1.BindData();
        }


        /// <summary>
        /// 显示客户信息
        /// </summary>
        private void DisplayClientInfo()
        {
            var cm = new Components.CM();
            //得到客户信息
            using (var dr_client = cm.GetClientInfo(_clientId))
            {
                while (dr_client.Read())
                {
                    ltl_ClientName.Text = dr_client["Name"].ToString();
                    ltl_ClientShortName.Text = dr_client["ShortName"].ToString();
                    ltl_ContactTimes.Text = dr_client["ContactTimes"].ToString();
                    ltl_Birthday.Text = dr_client["Birthday"].ToString();
                    ltl_UpdateTime.Text = dr_client["UpdateTime"].ToString();
                    ltl_fee.Text = dr_client["Fee"].ToString();
                    lbl_BargainPrognosis.Text = dr_client["BargainPrognosis"].ToString();
                    ltl_sellphase.Text = GetCurStatus(dr_client["sellphase"].ToString());
                }
                dr_client.Close();
            }
        }

        private static string GetCurStatus(string curstatus)
        {
            switch (curstatus.Split(',')[0])
            {
                case "trace":
                    return ("跟踪");

                case "boot":
                    return ("启动");

                case "commend":
                    return ("产品推荐");

                case "requirement":
                    return ("需求定义");

                case "submit":
                    return ("方案提交");

                case "negotiate":
                    return ("商务谈判");

                case "actualize":
                    return ("项目实施");

                case "traceservice":
                    return ("跟踪服务");

                case "last":
                    return ("收尾款");
            }
            return ("");
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            var cm = new Components.CM();
            var contact = new Contact();
            ClientInfo client = cm.GetClientAllInfo(_clientId);
            //添加协同人员
            foreach (ListItem lt in lbx_Cooperater.Items)
            {
                var cooperater = new Cooperater();
                cooperater.StaffID = Int32.Parse(lt.Value);
                contact.AddCooperater(cooperater);
            }
            //添加联系人员
            foreach (ListItem lt in lbx_Linkman.Items)
            {
                var linkman = new Components.Linkman();
                linkman.ID = Int32.Parse(lt.Value);
                contact.AddLinkman(linkman);
            }

            contact.ID = _contactId;

            #region 填充contact

            contact.UpdateTime = DateTime.Now;
            contact.ContactTimes = Int32.Parse(ltl_ContactTimes.Text);
            contact.StaffID = client.AddManID;
            contact.ContactTime = DateTime.Parse(tbx_contacttime.Text);
            contact.ClientID = _clientId;
            contact.ContactAim = tbx_contactaim.Text;
            contact.SellMoney = tbx_sellmoney.Text;
            contact.BargainPrognosis = ddl_bargainprognosis.SelectedItem.Value;
            if (cbx_telephone.Checked)
            {
                contact.ContactType += ContactType.telephone + ",";
            }
            if (cbx_fax.Checked)
            {
                contact.ContactType += ContactType.fax + ",";
            }
            if (cbx_email.Checked)
            {
                contact.ContactType += ContactType.email + ",";
            }
            if (cbx_mail.Checked)
            {
                contact.ContactType += ContactType.mail + ",";
            }
            if (cbx_sms.Checked)
            {
                contact.ContactType += ContactType.sms + ",";
            }
            if (cbx_callin.Checked)
            {
                contact.ContactType += ContactType.interview + ",";
            }
            if (cbx_meeting.Checked)
            {
                contact.ContactType += ContactType.meeting + ",";
            }

            if (rbtn_trace.Checked)
            {
                contact.ContactStatus += ContactStat.trace + ",";
            }
            if (rbtn_boot.Checked)
            {
                contact.ContactStatus += ContactStat.boot + ",";
            }
            if (rbtn_commend.Checked)
            {
                contact.ContactStatus += ContactStat.commend + ",";
            }
            if (rbtn_requirement.Checked)
            {
                contact.ContactStatus += ContactStat.requirement + ",";
            }
            if (rbtn_submit.Checked)
            {
                contact.ContactStatus += ContactStat.submit + ",";
            }
            if (rbtn_negotiate.Checked)
            {
                contact.ContactStatus += ContactStat.negotiate + ",";
            }
            if (rbtn_actualize.Checked)
            {
                contact.ContactStatus += ContactStat.actualize + ",";
            }
            if (rbtn_traceservice.Checked)
            {
                contact.ContactStatus += ContactStat.traceservice + ",";
            }
            if (rbtn_last.Checked)
            {
                contact.ContactStatus += ContactStat.last + ",";
            }

            contact.ThisFee = float.Parse(tbx_thisfee.Text);
            if (cbx_travel.Checked)
            {
                contact.FeeUsed += ContactFeeUsed.travel + ",";
            }
            if (cbx_food.Checked)
            {
                contact.FeeUsed += ContactFeeUsed.food + ",";
            }
            if (cbx_gift.Checked)
            {
                contact.FeeUsed += ContactFeeUsed.gift + ",";
            }
            if (cbx_out.Checked)
            {
                contact.FeeUsed += ContactFeeUsed.outer + ",";
            }
            contact.ContactContent = tbx_contactcontent.Text;
            contact.NextContactAim = tbx_nextcontactaim.Text;
            contact.NextContactTime = DateTime.Parse(tbx_nextcontacttime.Text);

            #endregion

            //如果contactid==0则插入操作，否则修改
            if (_contactId == 0)
            {
                contact.ContactTimes++;
                contact.ID = cm.AddContact(contact);
                _contactId = contact.ID;
                ViewState["ContactID"] = contact.ID.ToString();
                Response.Write("<script>alert('添加成功！');close();opener.document.location.href=opener.document.location.href</script>");
            }
            else
            {
                cm.UpdateContact(contact);
                Response.Write("<script>alert('修改成功！');close();</script>");
            }

            //修改client信息

            client.BargainPrognosis = contact.BargainPrognosis;
            client.ContactTimes = contact.ContactTimes;
            client.CurStatus = contact.ContactStatus;
            client.SellPhase = contact.ContactStatus;
            client.Fee += contact.ThisFee;
            client.UpdateTime = contact.UpdateTime;
            client.ContactTime = contact.ContactTime;
            client.NextContactTime = DateTime.Parse(tbx_nextcontacttime.Text);
            if (client.FirstContactTime == DateTime.Parse("1900-1-1"))
            {
                client.FirstContactTime = contact.ContactTime;
            }
            cm.UpdateClient(client);
            DisplayClientInfo();

            //上传附件
            UploadAtt();

            ControlClientContactHistory1.ClientID = _clientId;
            ControlClientContactHistory1.BindData();
        }

#if false
        private void btn_search_Click(object sender, EventArgs e)
        {
            string sqlstr = "";
            string id = "";
            var db = new Database();
            SqlDataReader dr = null;

            sqlstr = "select top 1 id from UDS_CM_ClientInfo WHERE name like '%" + tbx_quicksearch.Text.Replace("'", "''") + "%' and AddmanID=" + SiteContext.Current.UserID;
            var prams = new[] {
                                       Database.MakeInParam("@SQL", SqlDbType.NText, 5000, sqlstr)
                                   };
            dr = db.RunDataReader("dbo.sproc_RunSQL", prams);
            while (dr.Read())
            {
                id = dr["id"].ToString();
            }
            dr.Close();
            if (id != "")
            {
                foreach (ListItem lt in ddl_ClientName.Items)
                {
                    if (lt.Value == id)
                    {
                        lt.Selected = true;
                    }
                    else
                    {
                        lt.Selected = false;
                    }
                }
                clientid = Int32.Parse(id);
                DisplayClientInfo();
                BindData();
            }
        }
#endif

        private void ddl_ClientName_SelectedIndexChanged(object sender, EventArgs e)
        {
            _clientId = Int32.Parse(ddl_ClientName.SelectedItem.Value);
            ViewState["ClientID"] = _clientId;
            lbx_Cooperater.Items.Clear();
            lbx_Linkman.Items.Clear();
            DisplayClientInfo();
            BindData();
        }

        /// <summary>
        /// 上载文件
        /// </summary>
        private void UploadAtt()
        {
            var FrmCompose = (HtmlForm)Page.FindControl("ClientContact");
            var cm = new Components.CM();

            string FileName;
            string Extension;
            string SavedName;
            try
            {
                if (Directory.Exists(Server.MapPath(".") + "\\Attachment"))
                {
                    for (int i = 0; i < FrmCompose.Controls.Count; i++)
                    {
                        if (FrmCompose.Controls[i].GetType().ToString() == "System.Web.UI.HtmlControls.HtmlInputFile")
                        {
                            var hif = ((HtmlInputFile)(FrmCompose.Controls[i]));
                            if (hif.PostedFile.FileName.Trim() != "")
                            {
                                FileName = Path.GetFileName(hif.PostedFile.FileName);
                                Extension = Path.GetExtension(hif.PostedFile.FileName);

                                SavedName = cm.InsertFile(FileName, "contact", _contactId, Extension).ToString();

                                hif.PostedFile.SaveAs(Server.MapPath(".") + "\\Attachment\\" + SavedName + Extension);
                            }
                        }
                    }
                }
                else
                {
                    Directory.CreateDirectory(Server.MapPath(".") + "\\Attachment");
                    UploadAtt();
                }
            }
            catch (Exception ioex)
            {
                Logger.Log(ioex.ToString());
                Server.Transfer("../Error.aspx");
            }
        }

#if false
        private void rbtn_trace_CheckedChanged(object sender, EventArgs e)
        {
        }
#endif

        private void btn_in_Click(object sender, EventArgs e)
        {
            var selecteditem = new ArrayList();
            foreach (ListItem lt in lbx_Staff.Items)
            {
                if (lt.Selected)
                {
                    lbx_Cooperater.Items.Add(lt);
                    selecteditem.Add(lt);
                }
            }
            for (int i = 0; i < selecteditem.Count; i++)
            {
                lbx_Staff.Items.Remove((ListItem)selecteditem[i]);
            }
            BindData();
        }

        private void btn_out_Click(object sender, EventArgs e)
        {
            var selecteditem = new ArrayList();
            foreach (ListItem lt in lbx_Cooperater.Items)
            {
                if (lt.Selected)
                {
                    lbx_Staff.Items.Add(lt);
                    selecteditem.Add(lt);
                }
            }
            for (int i = 0; i < selecteditem.Count; i++)
            {
                lbx_Cooperater.Items.Remove((ListItem)selecteditem[i]);
            }
            BindData();
        }

        private void btn_inlinkman_Click(object sender, EventArgs e)
        {
            var selecteditem = new ArrayList();
            foreach (ListItem lt in lbx_ClientLinkman.Items)
            {
                if (lt.Selected)
                {
                    lbx_Linkman.Items.Add(lt);
                    selecteditem.Add(lt);
                }
            }
            for (int i = 0; i < selecteditem.Count; i++)
            {
                lbx_ClientLinkman.Items.Remove((ListItem)selecteditem[i]);
            }
            //BindData();
        }

        private void btn_outlinkman_Click(object sender, EventArgs e)
        {
            var selecteditem = new ArrayList();
            foreach (ListItem lt in lbx_Linkman.Items)
            {
                if (lt.Selected)
                {
                    lbx_ClientLinkman.Items.Add(lt);
                    selecteditem.Add(lt);
                }
            }
            for (int i = 0; i < selecteditem.Count; i++)
            {
                lbx_Linkman.Items.Remove((ListItem)selecteditem[i]);
            }
            //BindData();
        }

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN：该调用是 ASP.NET Web 窗体设计器所必需的。
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// 设计器支持所需的方法 - 不要使用代码编辑器修改
        /// 此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.ddl_ClientName.SelectedIndexChanged += new System.EventHandler(this.ddl_ClientName_SelectedIndexChanged);
            this.btn_in.Click += new System.EventHandler(this.btn_in_Click);
            this.btn_out.Click += new System.EventHandler(this.btn_out_Click);
            this.btn_inlinkman.Click += new System.EventHandler(this.btn_inlinkman_Click);
            this.btn_outlinkman.Click += new System.EventHandler(this.btn_outlinkman_Click);
            this.btn_OK.Click += new System.EventHandler(this.btn_OK_Click);
            this.Load += new System.EventHandler(this.Page_Load);
        }

        #endregion
    }
}